﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyCommunity.Models;
using System.Web.Security;
using MyCommunity.DataAccess;

public class UserDAL : IUserDAL
{
    //datacontext for entity framework
    private readonly MyCommunityDataContext _db;

    public UserDAL()
    {
        _db = new MyCommunityDataContext();
    }

    public User GetUser(int id)
    {
        return _db.User.Single(i => i.Id == id);
    }

    public User GetUser(String mail)
    {
        return _db.User.Where(i => i.Mail.Equals(mail)).SingleOrDefault();
    }

    public User GetUser(String mail, String password)
    {
        return _db.User.Where(i => i.Mail.Equals(mail) && i.Password.Equals(password)).SingleOrDefault();
    }


    public List<User> GetAllUsers()
    {
        return _db.User.Where(i => i.Id < 100).ToList();   
        // return _db.User.ToList(); Wenn Page Break eingefügt, dann wieder diesen Code verwenden
    }

    public List<User> FindUsers(String searchString)
    {
        string[] names =  searchString.Split(new char[] {' '} );
        
        if (names.Length == 2)
        {
            return _db.User.Where(s => s.Lastname.Contains(names[1]) && s.Firstname.Contains(names[0])).ToList();
        }

        return _db.User.Where(s => s.Lastname.Contains(searchString) || s.Firstname.Contains(searchString) || s.Mail.Contains(searchString)).ToList();
    }

    public void Add(User user)
    {
        _db.User.InsertOnSubmit(user);
    }

    public void Save()
    {
        _db.SubmitChanges();
    }
}